using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using MiniJSONx;
/// <summary>
/// Patterned like ItemHelper.cs.
/// I do not own ItemHelper.cs.
/// </summary>
public class ProfileReader : MonoBehaviour
{
	public static Dictionary<int, ProfileData> EXOGENESIS_PROFILES;

	//Load this before anything else!
	public static void LoadProfileList()
	{
		//creates an instance of Exo_Profiles Dictionary
		EXOGENESIS_PROFILES = new Dictionary<int, ProfileData>();

		//Loads external .txt file
		TextAsset profileData = Resources.Load("Profiles-Data", typeof(TextAsset)) as TextAsset; //implicit conversion is required

		Hashtable ht = Json.Deserialize(profileData.text) as Hashtable; //implicit conversion is required
		ArrayList jsonContents = ht["Profiles"] as ArrayList; //implicit conversion is required

		foreach(Hashtable item in jsonContents)
		{
			ProfileData toAdd = new ProfileData();

			toAdd.ID = int.Parse(item["id"].ToString());
			toAdd.name = item["name"].ToString();
			toAdd.imageDataPath = item["image"].ToString();
			toAdd.imageThumbnailDataPath = item["thumbnail"].ToString();
			toAdd.description = item["description"].ToString();

			EXOGENESIS_PROFILES.Add(toAdd.ID, toAdd);
		}

		Debug.Log("Loaded " + EXOGENESIS_PROFILES.Values.Count + " profiles");
	}

	public static void SaveProfileList(List<ProfileData> updatedProfiles)
	{
		Debug.Log(Application.dataPath + "/Resources/Profiles-Data.txt");
		string filePath = Application.dataPath + "/Resources/Profiles-Data.txt";
		StreamWriter sw = new StreamWriter(filePath);
		sw.Write(ConvertDictionaryToJSON(updatedProfiles));
		sw.Close();
	}

	public static ProfileData GetProfileByID(int key)
	{
		if(EXOGENESIS_PROFILES.ContainsKey(key))
			return EXOGENESIS_PROFILES[key];
		else
			return null;
	}

	public static ProfileData GetProfileByName(string key)
	{
		foreach(var prof in EXOGENESIS_PROFILES)
		{
			if(prof.Value.name.Contains(key))
				return prof.Value;
		}

		return null;
	}

	public static string ConvertDictionaryToJSON(List<ProfileData> profiles)
	{
		string ret = "{\n\t\"Profiles\" : [\n";
		ProfileData[] profilesToWrite = new ProfileData[profiles.Count];
		profiles.CopyTo(profilesToWrite, 0);

		for(int i = 0; i < profilesToWrite.Length; i++)
		{
			ret = ret + "\t\t{\n";
			ret = ret + "\t\t\t\"id\" : \"" + profilesToWrite[i].ID + "\",\n";
			ret = ret + "\t\t\t\"name\" : \"" + profilesToWrite[i].name + "\",\n";
			ret = ret + "\t\t\t\"image\" : \"" + profilesToWrite[i].imageDataPath + "\",\n";
			ret = ret + "\t\t\t\"thumbnail\" : \"" + profilesToWrite[i].imageThumbnailDataPath + "\",\n";
			ret = ret + "\t\t\t\"description\" : \"" + profilesToWrite[i].description + "\",\n";
			ret = ret + "\t\t}";

			if(i != profilesToWrite.Length - 1)
				ret = ret + ",\n";
		}

		return ret;
	}

	public static string SanitizeString(string text)
	{
		text = text.Replace("&line", "\n");
		text = text.Replace("&quot", "\"");

		return text;
	}
}

